package com.huluobo.a2307douyindemo.home

import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.huluobo.a2307douyindemo.MainViewModel
import com.huluobo.a2307douyindemo.adapter.HomeAdapter
import com.huluobo.a2307douyindemo.databinding.FragmentHomeBinding
import com.huluobo.a2307douyindemo.search.SearchActivity
import com.huluobo.a2307douyindemo.utils.ImageUtils
import com.huluobo.lib_base.event.MessageEvent
import com.huluobo.lib_base.mvvm.BaseFragment
import com.youth.banner.loader.ImageLoader
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    private lateinit var homeAdapter: HomeAdapter
    override fun initData() {
        vm.getHomeVideo(1, 40)
        vm.getHomeVideoSuccess.observe(this) {
            homeAdapter.data.clear()
            homeAdapter.data.addAll(it)
            homeAdapter.notifyDataSetChanged()
        }

        vm.getHomeBanner()
        vm.getHomeBannerSuccess.observe(this) {
            val bannerList = mutableListOf<String>()
            it.forEach {
                bannerList.add(it.imagePath)
            }
            binding.homeBanner.setImages(bannerList)
            binding.homeBanner.start()
        }
    }

    override fun initView() {
        binding.homeBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    ImageUtils.loadImage(context, path.toString(), imageView)
                }
            }
        })
        binding.homeRv.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        homeAdapter = HomeAdapter()
        binding.homeRv.adapter = homeAdapter

        binding.homeSearch.setOnClickListener {
            val intent = Intent(requireContext(), SearchActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onEvent(event: MessageEvent) {
        Log.e("TagA", "home接受:${event.message}")
    }
}